<?php 
/**
 * 更新天气预警，每2小时执行1次
 */
set_time_limit(300);
chdir("/data/www/w.mdeve.com/htdocs/");
require 'runtime.php';

$db = init_db();

// 开始从分流服务器更新，如果分流服务器挂了则重新搜索可用服务器，直到搜到能用为止
$ex_arr = array(-1);
try{
	// 从缓存中获取分流服务器列表，如果没有则创建
	$shunt_server = array();
	if($cache->exists("weather:server")){
		$shunt_server = $cache->fetch("weather:server");
	}else{
		$shunt_server = $db->get_rows("select id,server,weights,content from weather_server where hidden=0");
		if(false === $shunt_server) exit("err:06");
		$cache->store("weather:server");
	}
	// 如果分流服务器挂了则重新搜索可用服务器，直到搜到能用为止
	for($x=0;$x<sizeof($shunt_server);$x++){
		$i = get_randnum($shunt_server, $ex_arr);
		$url = str_replace("{action}", "alarm", $shunt_server[$i]['server']);
		$s = get_file($url);
		if(strlen($s)<128){
			$ex_arr[] = $i;
		}else{
			break;
		}
	}

	$bytes_update = strlen($s);	// 更新字节
	$s = base64_decode($s);
	if(strlen($s)<33) die ("Server {$i} read alarm error!<br />");
	$s = substr($s,0,strlen($s)-32);
	$s = @gzuncompress($s);
	if(strlen($s)<33) die ("Server {$i} read alarm error!!<br />");
	$alarm_data = unserialize($s);
	
	// 更新完成后修改服务器更新量
	$bytes_grab = $alarm_data["in_flow"];
	$db->query("update weather_server set num=num+1,lastupdate=now(),lastcity='预警信息',bytes_grab=bytes_grab+{$bytes_grab},bytes_update=bytes_update+$bytes_update where id=". $shunt_server[$i]["id"]);
	// 清空预警数据表
	$db->query("TRUNCATE TABLE `weather_alarm`");
	foreach($alarm_data as $r){
		if(!is_array($r)) continue;	// 如果$r不是数组则跳过，不是数组的用来记录流量等信息
		if(!strlen($r["issuetime"])) continue;		// 如果数据没同步
		$db->query("insert into weather_alarm(province,city,signaltype,signallevel,issuetime,issuecontent) values(
			'".str_replace(array(",","%"),"", $r["province"])."',
			'".str_replace(array(",","%"),"", $r["city"])."',
			'".str_replace(array(",","%"),"", $r["signaltype"])."',
			'".str_replace(array(",","%"),"", $r["signallevel"])."',
			'".str_replace(array(",","%"),"", $r["issuetime"])."',
			'".str_replace(array(",","%"),"", $r["issuecontent"])."'
		)");
	}
	echo "done\r\n";

}catch(PDOException $e){
	die ("Server {$i} read error!<br /><br />" . $e->getMessage() . "<br />");
}


?>